import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../API/admin/admin.dart';
import '../../../data/shared_preferences_service.dart';
import '../../admin/admin.dart';

class AdminLoginController extends GetxController {
  final RxBool showPassword = false.obs;
  final RxBool isChecked = false.obs;
  final RxString name = ''.obs;
  final RxString password = ''.obs;
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  Future<void> login() async {
    if (formKey.currentState != null && formKey.currentState!.validate()) {
      formKey.currentState!.save();

      final response = await AdminApiService.login(username:name.value, password:password.value);
      final int code = response["code"];

      if (code == 10021) {
        await SharedPreferencesService.saveToken(response["data"]);
        Get.offAll(const AdminView());
        Get.snackbar("登陆成功", "", snackPosition: SnackPosition.TOP);
      } else {
        Get.snackbar(
          code == 10020 ? "账号或密码错误" : "未知错误",
          code != 10020 ? "登陆失败: ${response['message']}" : "",
          snackPosition: SnackPosition.TOP,
          duration: Duration(seconds: code == 10020 ? 2 : 5),
        );
      }
    }
  }
}

class AdminLoginPage extends StatelessWidget {
  AdminLoginPage({super.key});
  final AdminLoginController controller = Get.put(AdminLoginController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: const Color(0xFF0088FF),
        foregroundColor: Colors.white,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: Get.back,
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF0088FF), Colors.cyanAccent],
          ),
        ),
        child: ListView(
          children: [
            const SizedBox(height: 40),
            _buildWelcomeText(),
            _buildLoginForm(),
          ],
        ),
      ),
    );
  }

  Widget _buildWelcomeText() {
    return const Padding(
      padding: EdgeInsets.all(40),
      child: Text(
        '管理员登陆',
        style: TextStyle(
          color: Colors.white,
          fontSize: 32,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildLoginForm() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(40, 0, 40, 0),
      child: Form(
        key: controller.formKey,
        child: Column(
          children: [
            _buildPhoneField(),
            const SizedBox(height: 20),
            _buildPasswordField(),
            const SizedBox(height: 40),
            _buildLoginButton(),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  Widget _buildPhoneField() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '账号',
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(color: Colors.white),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      onSaved: (value) => controller.name.value = value ?? '',
      validator: (value) => value?.isEmpty ?? true ? '请输入账号' : null,
    );
  }

  Widget _buildPasswordField() {
    return Obx(() => TextFormField(
      decoration: InputDecoration(
        labelText: '密码',
        hintText: '请输入密码',
        labelStyle: const TextStyle(color: Colors.white),
        hintStyle: const TextStyle(color: Colors.white),
        suffixIcon: IconButton(
          icon: Icon(
            controller.showPassword.value
                ? Icons.visibility_off
                : Icons.visibility,
            color: Colors.white,
          ),
          onPressed: controller.showPassword.toggle,
        ),
        enabledBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      onSaved: (value) => controller.password.value = value ?? '',
      obscureText: !controller.showPassword.value,
      validator: (value) => (value?.length ?? 0) < 6 ? '密码最少六个字符' : null,
    ));
  }

  Widget _buildLoginButton() {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.white,
        foregroundColor: Colors.blue,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        padding: const EdgeInsets.symmetric(horizontal: 80),
      ),
      onPressed: controller.login,
      child: const Text('登录'),
    );
  }


}